<?php
/**
 * @file tags.php
 * @author CaoQiCheng
 * @date 2017年2月8日 下午17:05:11
 * @brief 
 */
namespace haibao\jiepai\data;


class AppVersions extends \haibao\jiepai\data\BaseMysql{	
	public function __construct(){
		parent::__construct('\haibao\jiepai\model\data\app\CmsAppVersions');
	}
	
	public function saveAppVersion($model,$imageIdArr){
		$this->beginTranscation();
		try {
			if($model->Id){
				$this->save($model);
			}else {
				$this->add($model);
			}
			$this->saveAppVersionPicture($model->Id, $imageIdArr);
		} catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	/**
	 * 增加合作的品牌关联
	 */
	public function saveAppVersionPicture($appVersionId,$imageIdArr){
		if(!$appVersionId){
			return false;
		}
		$dateTime = new \DateTime();
		$this->query('update `cms_app_versions_pictures` set Flag=-1 where VersionID = %s', array(
				$appVersionId
		));
		if(isset($imageIdArr) && $imageIdArr){
			$sql = 'insert into cms_app_versions_pictures(VersionID,FileID,ShowIndex,Flag,CreateTime) values ';
			$arrSql = $arrValues = array();
			foreach($imageIdArr as $key=>$val){
				array_push($arrSql, '(%s,%s,%s,%s,%s)');
				array_push($arrValues, $appVersionId);
				array_push($arrValues, $val);
				array_push($arrValues, 0);
				array_push($arrValues, 0);
				array_push($arrValues, $dateTime);
			}
			if($arrSql && $arrValues){
				$sql .= implode(',', $arrSql);
				$this->query($sql, $arrValues);
			}
		}
	}
	
	public function GetAPPVersionUpdate($phoneOsType){
		$sql = "SELECT ID as VersionID,AppVersion,Title,Description,AppleUrl,AndroidUrl,Status as IsForceUpdate FROM `cms_app_versions` WHERE Flag = 0 and PhoneOS in (3, " . $phoneOsType . ") AND UpdateTime <= NOW() ORDER BY UpdateTime DESC LIMIT 1;";
		$result = $this->query($sql);
		$list = array();
		while($row = $result->fetch_assoc()){
			array_push($list, $row);
		}
		return $list;
	
	}
	
	public function GetAppForceUpdateVersion($phoneOsType){
		$sql = "SELECT AppVersion FROM `cms_app_versions` WHERE Flag = 0 and PhoneOS in (3, " . $phoneOsType . ") AND UpdateTime <= NOW() AND Status=1 ORDER BY UpdateTime DESC LIMIT 1;";
		$result = $this->query($sql);
		$list = array();
		while($row = $result->fetch_assoc()){
			array_push($list, $row);
		}
		
		return isset($list[0]) && $list[0]['AppVersion'] ? $list[0]['AppVersion'] : '4.0.0';
	}
	
}